<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\common\Platform;
use app\common\UserService;
use app\job\Task;
use app\model\GoodsOrders;
use app\model\ShopOrders;
use app\model\SuperOrders;
use app\model\UserMoneyLog;
use app\model\UserRechargeLog;
use app\model\UserWithdraw;
use think\facade\Log;
use think\facade\Queue;
use think\Request;
use Yansongda\Pay\Pay;

class NotifyController extends BaseController
{
    function ossNotify()
    {
        Log::debug($this->request->param());
        $this->writeJson();
    }

    function withdrawNotify()
    {
        $params = $this->request->param();
        Log::record('提现回调');
        Log::record($params);
        $this->writeJson();
    }

    function goodsOrderConfirm()
    {
        $order_id = $this->request->param('order_id');
        Queue::later(60 * 60 * 24 * 7, Task::class, ['order_id' => $order_id, 'action' => 'goods_order_confirm'], 'task');
        $this->writeJson();
    }

    public function returnNotify()
    {
        $paytype = $this->request->param('paytype');
        $config = config('pay');
        switch ($paytype) {
            case 'wechat':
                $pay = Pay::wechat($config);
                try {
                    $res = $pay->callback();
                } catch (\Exception $e) {
                    $this->writeJson(0, '验签错误');
                }
                $res = $res->resource;
                $res = $res['ciphertext'];
                $out_trade_no = $res['out_trade_no'];
                $attach = $res['attach'];
                $mchid = $res['mchid'];
                $transaction_id = $res['transaction_id'];
                $openid = $res['payer']['openid'] ?? '';
                break;
            case 'alipay':
                $pay = Pay::alipay($config);
                try {
                    $res = $pay->callback();
                } catch (\Exception $e) {
                    $this->writeJson(0, $e->getMessage());
                }
                $out_trade_no = $res->out_trade_no;
                $attach = $res->passback_params;
                break;
            case 'balance':
                $out_trade_no = $this->request->param('out_trade_no');
                $attach = $this->request->param('attach');
                break;
            default:
                $this->writeJson(0, '支付类型错误');
        }

        switch ($attach) {
            case 'goods':
                $order = GoodsOrders::where(['order_sn' => $out_trade_no, 'status' => 1])->find();
                if (!$order) {
                    $this->writeJson(0, '订单不存在');
                }
                $order->status = 2;
                $order->paytime = time();
                $order->goods->sales += 1;
                if (empty($order->user->first_buy_goods_time)) {
                    //如果是第一次买精品区
                    $order->user->first_buy_goods_time = time();
                    #给自己增加贡献值
                    UserService::changeUserGoodsDevote($order->goods->spec->devote, $order->user_id, '购买精品区商品');
                    if ($order->user->parent) {
                        $parent = $order->user->parent;
                        #给上级反贡献值
                        UserService::changeUserGoodsDevote($order->goods->spec->devote, $parent->id, '好友购买精品商品');
                    }
                }
                if ($order->user->parent) {
                    $parent = $order->user->parent;
                    #给上级反推荐奖
                    if ($parent->goods_quota > 0) {
                        $money = $order->pay_amount * 0.2;
                        if ($money > $parent->goods_quota) {
                            $money = $parent->goods_quota;
                        }
                        UserService::changeUserGoodsQuota(-$money, $parent->id, '精品区推荐分红扣除');
                        UserService::changeUserMoney($money, $parent->id, '精品区推荐奖');
                    }
                }
                #给自己增加精品区分红额度
                UserService::changeUserGoodsQuota($order->goods->spec->quota, $order->user_id, '购买商品奖励');
                $order->together(['goods', 'user'])->save();
                break;
            case 'super':
                $order = SuperOrders::where(['order_sn' => $out_trade_no, 'status' => 1])->find();
                if (!$order) {
                    $this->writeJson(0, '订单不存在');
                }
                $supply_price = 0;
                foreach ($order->detail as $item) {
                    $supply_price += $item->spec->supply_price;
                }
                $order->status = 2;
                $order->supply_price = $supply_price;
                $order->paytime = time();
                #给自己增加优选区分红额度
                UserService::changeUserSuperQuota($order->pay_amount * 1.3, $order->user_id, '购买优选商品');
                if ($order->user->parent) {
                    $parent = $order->user->parent;
                    #给上级反推荐奖
                    UserService::changeUserMoney($order->pay_amount * 0.01, $parent->id, '优选区推荐奖');
                }
                $order->save();
                break;
            case 'shop':
                $order = ShopOrders::where(['order_sn' => $out_trade_no, 'status' => 1])->find();
                if (!$order) {
                    $this->writeJson(0, '订单不存在');
                }
                $order->status = 2;
                $order->paytime = time();
                $order->save();
                #给自己增加消费者分红额度
                UserService::changeUserShopQuota($order->pay_amount * 4, $order->user_id, '购买商家优惠券');
                #增加商家分红额度
                UserService::changeUserShopQuota($order->pay_amount, $order->shop->user_id, '用户购买优惠券');
                #5%分给 商家推广员
                UserService::changeUserMoney($order->pay_amount * 0.05, $order->shop->parent->id, '推广员商铺订单提成');
                #5%分给 推荐人
                UserService::changeUserMoney($order->pay_amount * 0.05, $order->shop->user->parent->id, '下级商铺订单提成');
                break;
            case 'recharge':
                $order = UserRechargeLog::where(['order_sn' => $out_trade_no, 'status' => 1])->find();
                $order->status = 2;
                $order->paytime = time();
                $order->save();
                #增加余额
                UserService::changeUserMoney($order->amount, $order->user_id, ($paytype == 'alipay' ? '支付宝' : '微信') . '充值余额');
                break;
            default:
                $this->writeJson(0, '回调错误');
        }

        switch ($paytype) {
            case 'wechat':
                if ($order->pay_source == 'wechatmini') {
                    #默认发货
                    Platform::uploadShippingInfo($transaction_id, $mchid, $openid);
                }
                $pay->success();
                break;
            case 'alipay':
                $pay->success();
                break;
            case 'balance':
                return true;
            default:
                $this->writeJson(0, '支付类型错误');
        }

    }
}
